package com.rabbit.eap.framework.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @projectName eap
 * @packageName com.rabbit.eap.framework.utils
 * @className IpUtil
 * @author： rabbit
 * @version： 1.0
 * @since： 2020/4/19 19:47
 * <p>Description: IpUtil </p>

 */
public class IpUtil {
    public final static String HEADER1 = "x-forwarded-for";
    public final static String HEADER2 = "Proxy-Client-IP";
    public final static String HEADER3 = "WL-Proxy-Client-IP";
    public final static String UNKNOWN = "unknown";
    public final static String LOCALHOST = "127.0.0.1";
    private static final String IPV6_LOCAL = "0:0:0:0:0:0:0:1";

    private IpUtil(){
        throw new AssertionError();
    }

    /**
     * 获取请求用户的IP地址
     * @return
     */
    public static String getRequestIp() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        return getRequestIp(request);
    }

    /**
     * 获取请求用户的IP地址
     * @param request
     * @return
     */
    public static String getRequestIp(HttpServletRequest request) {
        String ip = request.getHeader(HEADER1);
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(HEADER2);
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(HEADER3);
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if (IPV6_LOCAL.equals(ip)){
            ip = getHostIp();
        }
        return ip;
    }

    public static String getHostIp(){
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
        }
        return null;
    }
    public static String getHostName()
    {
        try
        {
            return InetAddress.getLocalHost().getHostName();
        }
        catch (UnknownHostException e)
        {
        }
        return UNKNOWN;
    }

}
